from rest_framework import serializers
from article.models import Article


class StateChoiceField(serializers.ChoiceField):
    def to_internal_value(self, data):
        # To support inserts with the value
        if data == '' and self.allow_blank:
            return ''

        for key, val in self._choices.items():
            if val == data:
                return key
        self.fail('invalid_choice', input=data)


class ArticleSerializer(serializers.ModelSerializer):
    STATE_CHOICES = (
        (1, "已发布"),
        (2, "草稿")
    )
    state = StateChoiceField(choices=STATE_CHOICES)

    class Meta:
        model = Article
        fields = ('title', 'content', 'state', 'cate_id', 'author_id', 'pub_date')

    def create(self, validated_data):
        return Article.objects.create(**validated_data)


class ArticleListSerializer(serializers.Serializer):
    """文章列表序列化器"""

    STATE_CHOICES = (
        (1, "已发布"),
        (2, "草稿")
    )
    cate_name = serializers.StringRelatedField(source='cate_id')
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(max_length=100)
    pub_date = serializers.DateTimeField()
    state = serializers.SerializerMethodField()

    def get_state(self, key):
        return key.get_state_display()


class OneArticleSerializer(serializers.Serializer):
    """获取单个文章内容"""
    STATE_CHOICES = (
        (1, "已发布"),
        (2, "草稿")
    )
    cate_id = serializers.PrimaryKeyRelatedField(read_only=True)
    author_id = serializers.PrimaryKeyRelatedField(read_only=True)
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(max_length=100)
    content = serializers.CharField()
    cover_img = serializers.ImageField()
    pub_date = serializers.DateTimeField()
    state = serializers.SerializerMethodField()
    is_delete = serializers.BooleanField()

    def get_state(self, key):
        return key.get_state_display()


class EditArticleSerializer(serializers.ModelSerializer):
    """更新文章序列化器"""
    STATE_CHOICES = (
        (1, "已发布"),
        (2, "草稿")
    )
    state = StateChoiceField(choices=STATE_CHOICES)

    class Meta:
        model = Article
        fields = ('id', 'title', 'cate_id', 'cover_img', 'content', 'state')
